import axios from "axios";
import environment from "/environment";
import Vue from "vue";
import VueRouter from "vue-router";
import Router from "@/router";

Vue.use(VueRouter);

const request = axios.create({
  baseURL: environment,
  timeout: 10000,
  headers: { "X-Custom-Header": "foobar" },

  withCredentials: true, // 允许携带cookie
});

// request 拦截器
// 可以自请求发送前对请求做一些处理
// 比如统一加token，对请求参数统一加密
request.interceptors.request.use(
  (config) => {
    config.headers["Content-Type"] = "application/json;charset=utf-8";
    let token = sessionStorage.getItem("token");
    let userId = sessionStorage.getItem("userId");
    if (token != null || userId != null) {
      config.headers["token"] = token; // 设置请求头
      config.headers["userId"] = userId;
    }

    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

request.interceptors.response.use(function (response) {
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    debugger;
    if(response.data.message == "token为空请登录"){
        Router.push({name: "Login", params: { id: 1 }});
    }
    return response;
}, function (error) {

    return Promise.reject(error);
});

export default request;
